//package com.example.myapplication;
//
//import androidx.appcompat.app.AppCompatActivity;
//import android.annotation.SuppressLint;
//import android.os.Bundle;
//
//import android.widget.Button;
//import android.widget.TableLayout;
//import android.widget.TextView;
//
//import java.util.concurrent.Executors;
//import java.util.concurrent.ScheduledExecutorService;
//import java.util.concurrent.TimeUnit;
//
//import com.example.myapplication.bean.Photo;
//
//import android.database.sqlite.SQLiteDatabase;
//import android.database.Cursor;
//import android.widget.TableRow;
//import android.view.Gravity;
//
//// 定义一个功能类
//public class FunctionActivity extends AppCompatActivity {
//    // 定义私有成员变量
//    private static final String TAG = "FunctionActivity";
//    private Button btn_add; // 上传本地图片按钮
//    private ScheduledExecutorService scheduler; // 定时任务执行器
//
//    private MySQLiteOpenHelper dbHelper; // 数据库帮助类
//    private TableLayout tableLayout; // 显示图片信息的 TableLayout
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_function_main);
//
//        // 初始化 TableLayout
//        tableLayout = findViewById(R.id.tableLayout);
//
//        dbHelper = new MySQLiteOpenHelper(this); // 初始化数据库帮助类
//
//        // 获取layout的布局界面的元素对象
//        btn_add = findViewById(R.id.btn_add); // 获取添加按钮
//
//        // 设置按钮点击事件，上传手机的本地图片
//        btn_add.setOnClickListener(v -> {
//
//        });
//        displayFoodData(); // 刷新图片信息展示
//
//        /* -------------------------------------------------------------------------------------- */
//        // 启动定时器定期刷新表格
//        startTableRefresh();
//    }
//
//    private void startTableRefresh() {
//        // 启动定时器 + 线程池定期刷新table图片信息表
//        scheduler = Executors.newScheduledThreadPool(1);
//        scheduler.scheduleAtFixedRate(() -> {
//            runOnUiThread(this::displayFoodData);
//        }, 0, 2, TimeUnit.SECONDS); // 每2秒刷新一次表格
//    }
//
//    // 刷新表格，显示图片信息
//    private void displayFoodData() {
//        // 清空除表头之外的所有行
//        tableLayout.removeViewsInLayout(1, tableLayout.getChildCount() - 1);
//
//        SQLiteDatabase db = dbHelper.getReadableDatabase();
//        Cursor cursor = db.rawQuery("SELECT * FROM photos", null);
//
//        while (cursor.moveToNext()) {
//            // 获取数据
//            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
//            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
//            @SuppressLint("Range") String picture = cursor.getString(cursor.getColumnIndex("picture"));
//
//            // 创建新行
//            TableRow row = new TableRow(this);
//            // 这里可以设置行的属性，例如边距、背景等
//
//            // 创建各列的 TextView
//            TextView nameTextView = new TextView(this);
//            nameTextView.setText(name);
//            nameTextView.setGravity(Gravity.CENTER);
//
//            TextView storeDateTextView = new TextView(this);
//            storeDateTextView.setText(picture);
//            storeDateTextView.setGravity(Gravity.CENTER);
//
//            TextView countTextView = new TextView(this);
//            countTextView.setGravity(Gravity.CENTER);
//
//            TextView remainingDaysTextView = new TextView(this);
//            remainingDaysTextView.setGravity(Gravity.CENTER);
//
//            // 创建“下载”操作按钮
//            Button takeOutButton = new Button(this);
//            takeOutButton.setText("下载");
//            takeOutButton.setOnClickListener(v -> {
//                // 当点击“下载”按钮时，弹出对话框，并处理相应的下载服务器的图片到本地相册
//                Photo photo = new Photo(id, name, picture);
//                showTakeOutDialog(photo);
//            });
//
//            // 将各个组件添加到行中
//            row.addView(nameTextView);
//            row.addView(storeDateTextView);
//            row.addView(takeOutButton);
//
//            // 将行添加到 TableLayout
//            tableLayout.addView(row);
//        }
//
//        cursor.close();
//        db.close();
//    }
//    private void showTakeOutDialog(final Photo photo) {
//
//    }
//
//}




















/*
--------------------------------------------------------------------------------------------------------------------------------------
 */
package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.bean.Photo;
import com.github.mikephil.charting.BuildConfig;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class FunctionActivity extends AppCompatActivity {
    private static final String TAG = "FunctionActivity";

    private void log(String message) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, message);
        }
    }

    private Button btn_add;
    private ScheduledExecutorService scheduler;
    private MySQLiteOpenHelper dbHelper;
    private TableLayout tableLayout;
    private ProgressDialog progressDialog;
    private static final int PICK_IMAGE_REQUEST = 1;
    private ArrayList<String> selectedImagePaths = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_function_main);

        tableLayout = findViewById(R.id.tableLayout);
        btn_add = findViewById(R.id.btn_add);
        dbHelper = new MySQLiteOpenHelper(this);

        // 初始化进度对话框
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在处理...");
        progressDialog.setCancelable(false);

        // 设置上传按钮点击事件
        btn_add.setOnClickListener(v -> openImageChooser());

        // 首次加载数据
        loadServerImages();

//        // 启动定时刷新
//        startTableRefresh();
    }

    private void openImageChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            selectedImagePaths.clear();

            if (data.getClipData() != null) {
                // 多选图片
                int count = data.getClipData().getItemCount();
                for (int i = 0; i < count; i++) {
                    Uri imageUri = data.getClipData().getItemAt(i).getUri();
                    selectedImagePaths.add(getRealPathFromURI(imageUri));
                }
            } else if (data.getData() != null) {
                // 单选图片
                Uri imageUri = data.getData();
                selectedImagePaths.add(getRealPathFromURI(imageUri));
            }

            if (!selectedImagePaths.isEmpty()) {
                new UploadImagesTask().execute();
            }
        }
    }

    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor == null) return null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        cursor.close();
        return path;
    }

    private void startTableRefresh() {
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            runOnUiThread(this::displayPhotoData);
        }, 0, 5, TimeUnit.SECONDS); // 每5秒刷新一次
    }

    private void loadServerImages() {
        new LoadImagesTask().execute();
    }

    private void displayPhotoData() {
        tableLayout.removeViews(1, tableLayout.getChildCount() - 1);

        List<Photo> photos = dbHelper.getAllPhoto();

        if (photos == null || photos.isEmpty()) {
            TableRow row = new TableRow(this);
            TextView emptyText = new TextView(this);
            emptyText.setText("没有图片数据");
            emptyText.setGravity(Gravity.CENTER);
            row.addView(emptyText);
            tableLayout.addView(row);
            return;
        }

        for (Photo photo : photos) {
            TableRow row = new TableRow(this);
            row.setPadding(0, 10, 0, 10);

            // 名称列
            TextView nameTextView = new TextView(this);
            nameTextView.setText(photo.getName());
            nameTextView.setGravity(Gravity.CENTER);
            nameTextView.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1));

            // 图片预览列
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 4));
            imageView.setAdjustViewBounds(true);
            imageView.setMaxHeight(150);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

            // 异步加载图片
            new LoadImageTask(imageView).execute(photo.getPicture());

            // 下载按钮
            Button downloadButton = new Button(this);
            downloadButton.setText("下载");
            downloadButton.setOnClickListener(v -> {
                // 这里可以实现下载功能
                Toast.makeText(FunctionActivity.this, "下载: " + photo.getName(), Toast.LENGTH_SHORT).show();
            });

            row.addView(nameTextView);
            row.addView(imageView);
            row.addView(downloadButton);
            tableLayout.addView(row);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scheduler != null) {
            scheduler.shutdown();
        }
    }

    // 异步任务：从服务器加载图片列表
    private class LoadImagesTask extends AsyncTask<Void, Void, List<Photo>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.setMessage("正在从服务器加载图片...");
            progressDialog.show();
        }

        @Override
        protected List<Photo> doInBackground(Void... voids) {
            List<Photo> photos = new ArrayList<>();
            try {

                Log.d(TAG, "开始加载图片...");

                URL url = new URL("http://8.138.215.14/get_images.php");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");

                Log.d(TAG, "连接已建立，响应码: " + conn.getResponseCode());

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                String responseStr = response.toString();
                Log.d(TAG, "服务器响应: " + responseStr);
                // 然后继续解析JSON

                JSONObject jsonResponse = new JSONObject(response.toString());
                if (jsonResponse.getBoolean("success")) {
                    JSONArray images = jsonResponse.getJSONArray("images");
                    for (int i = 0; i < images.length(); i++) {
                        JSONObject image = images.getJSONObject(i);
                        Photo photo = new Photo();
                        photo.setName(image.getString("name"));
                        photo.setPicture(image.getString("url"));
                        photos.add(photo);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "加载图片错误: " + e.getMessage());
            }
            return photos;
        }

        @Override
        protected void onPostExecute(List<Photo> photos) {
            progressDialog.dismiss();

            if (photos == null) {
                Toast.makeText(FunctionActivity.this, "无法连接到服务器", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!photos.isEmpty()) {
                // 清空旧数据
                dbHelper.deleteAllPhotos();

                // 插入新数据
                for (Photo photo : photos) {
                    dbHelper.insertPhoto(photo);
                }

                // 刷新显示
                displayPhotoData();
            } else {
                Toast.makeText(FunctionActivity.this, "没有获取到图片数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 异步任务：上传图片到服务器
    private class UploadImagesTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            String result = "error";
            try {
                for (String imagePath : selectedImagePaths) {
                    File imageFile = new File(imagePath);
                    if (!imageFile.exists()) {
                        Log.e(TAG, "文件不存在: " + imagePath);
                        continue;
                    }

                    String boundary = "*****";
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";

                    URL url = new URL("http://8.138.215.14/upload.php");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                    // 添加文件部分
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"images[]\"; filename=\"" + imageFile.getName() + "\"" + lineEnd);
                    dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
                    dos.writeBytes(lineEnd);

                    FileInputStream fis = new FileInputStream(imageFile);
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, bytesRead);
                    }
                    fis.close();

                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    dos.flush();
                    dos.close();

                    // 检查响应
                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();
                        result = response.toString();
                    } else {
                        Log.e(TAG, "服务器返回错误代码: " + responseCode);
                    }
                    conn.disconnect();
                }
            } catch (Exception e) {
                Log.e(TAG, "上传图片错误: " + e.getMessage(), e);
                result = "error";
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            progressDialog.dismiss();
            if (result.equals("error")) {
                Toast.makeText(FunctionActivity.this, "上传失败，请检查网络连接", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                JSONObject jsonResponse = new JSONObject(result);
                if (jsonResponse.getBoolean("success")) {
                    int uploadedCount = jsonResponse.getInt("uploadedCount");
                    Toast.makeText(FunctionActivity.this,
                            "成功上传 " + uploadedCount + " 张图片", Toast.LENGTH_SHORT).show();
                    // 重新加载图片
                    new LoadImagesTask().execute();
                } else {
                    String message = jsonResponse.getString("message");
                    Toast.makeText(FunctionActivity.this,
                            "上传失败: " + message, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(FunctionActivity.this,
                        "上传结果解析错误", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "解析上传结果错误: " + e.getMessage());
            }
        }
    }

//    private class UploadImagesTask extends AsyncTask<Void, Void, String> {
//        @Override
//        protected void onPreExecute() {
//            super.onPreExecute();
//            progressDialog.setMessage("正在上传图片...");
//            progressDialog.show();
//        }
//
//        @Override
//        protected String doInBackground(Void... voids) {
//            String result = "";
//            try {
//                String boundary = "*****";
//                String lineEnd = "\r\n";
//                String twoHyphens = "--";
//
//                for (String imagePath : selectedImagePaths) {
//                    File imageFile = new File(imagePath);
//                    if (!imageFile.exists()) continue;
//
//                    URL url = new URL("http://8.138.215.14/upload.php");
//                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                    conn.setDoInput(true);
//                    conn.setDoOutput(true);
//                    conn.setUseCaches(false);
//                    conn.setRequestMethod("POST");
//                    conn.setRequestProperty("Connection", "Keep-Alive");
//                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//
//                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
//                    dos.writeBytes(twoHyphens + boundary + lineEnd);
//                    dos.writeBytes("Content-Disposition: form-data; name=\"images[]\"; filename=\"" + imageFile.getName() + "\"" + lineEnd);
//                    dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
//                    dos.writeBytes(lineEnd);
//
//                    FileInputStream fis = new FileInputStream(imageFile);
//                    byte[] buffer = new byte[1024];
//                    int bytesRead;
//                    while ((bytesRead = fis.read(buffer)) != -1) {
//                        dos.write(buffer, 0, bytesRead);
//                    }
//                    dos.writeBytes(lineEnd);
//                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
//
//                    fis.close();
//                    dos.flush();
//                    dos.close();
//
//                    // 读取响应
//                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                    StringBuilder response = new StringBuilder();
//                    String line;
//                    while ((line = reader.readLine()) != null) {
//                        response.append(line);
//                    }
//                    reader.close();
//                    result = response.toString();
//                }
//            } catch (Exception e) {
//                Log.e(TAG, "上传图片错误: " + e.getMessage());
//                result = "error";
//            }
//            return result;
//        }
//
//        @Override
//        protected void onPostExecute(String result) {
//            progressDialog.dismiss();
//            if (!result.equals("error")) {
//                try {
//                    JSONObject jsonResponse = new JSONObject(result);
//                    if (jsonResponse.getBoolean("success")) {
//                        Toast.makeText(FunctionActivity.this, "成功上传 " + jsonResponse.getInt("uploadedCount") + " 张图片", Toast.LENGTH_SHORT).show();
//                        // 重新加载服务器图片
//                        loadServerImages();
//                    } else {
//                        Toast.makeText(FunctionActivity.this, "上传失败: " + jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
//                    }
//                } catch (Exception e) {
//                    Toast.makeText(FunctionActivity.this, "上传结果解析错误", Toast.LENGTH_SHORT).show();
//                }
//            } else {
//                Toast.makeText(FunctionActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
//            }
//        }
//    }

    // 异步任务：加载单张图片
    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        private ImageView imageView;
        private String imageUrl;

        public LoadImageTask(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
            imageUrl = urls[0];
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                return BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                Log.e(TAG, "加载图片错误: " + imageUrl, e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                // 设置一个默认图片或显示错误提示
//                imageView.setImageResource(R.drawable.ic_broken_image);
                Log.e(TAG, "无法加载图片: " + imageUrl);
            }
        }
    }

//    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
//        private ImageView imageView;
//
//        public LoadImageTask(ImageView imageView) {
//            this.imageView = imageView;
//        }
//
//        @Override
//        protected Bitmap doInBackground(String... urls) {
//            String imageUrl = urls[0];
//            Bitmap bitmap = null;
//            try {
//                InputStream in = new URL(imageUrl).openStream();
//                bitmap = BitmapFactory.decodeStream(in);
//            } catch (Exception e) {
//                Log.e(TAG, "加载图片错误: " + e.getMessage());
//            }
//            return bitmap;
//        }
//
//        @Override
//        protected void onPostExecute(Bitmap bitmap) {
//            if (bitmap != null) {
//                imageView.setImageBitmap(bitmap);
//            }
//        }
//    }

////    其他改进建议
////    添加权限检查：
//    // 在Activity中检查存储权限
//    private boolean checkStoragePermission() {
//        if (ContextCompat.checkSelfPermission(this,
//                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this,
//                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
//                    STORAGE_PERMISSION_CODE);
//            return false;
//        }
//        return true;
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == STORAGE_PERMISSION_CODE) {
//            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                openImageChooser();
//            } else {
//                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
//            }
//        }
//    }

}